<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IM Client</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
        #login-form { max-width: 300px; margin: 0 auto; }
        #chat-container { display: flex; max-width: 800px; margin: 0 auto; }
        #user-list, #chat-window { border: 1px solid #ccc; padding: 10px; margin: 10px; }
        #user-list { width: 200px; }
        #chat-window { flex-grow: 1; }
        #message-list { height: 300px; overflow-y: scroll; border: 1px solid #eee; padding: 10px; }
        #message-input { width: calc(100% - 70px); }
        .message { margin-bottom: 10px; }
        .message .sender { font-weight: bold; }
        button { cursor: pointer; }
    </style>
</head>
<body>
<div id="login-form">
    <h2>Login or Register</h2>
    <input type="text" id="username" placeholder="Username">
    <input type="password" id="password" placeholder="Password">
    <button onclick="login()">Login</button>
    <button onclick="register()">Register</button>
</div>
<div id="chat-container" style="display: none;">
    <div id="user-list">
        <h3>Online Users</h3>
        <ul id="users"></ul>
    </div>
    <div id="chat-window">
        <div id="message-list"></div>
        <input type="text" id="message-input" placeholder="Type a message...">
        <button onclick="sendMessage()">Send</button>
    </div>
</div>

<script src="js/axios.min.js"></script>
<script>
    let currentUser = null;
    let socket = null;
    const messageList = document.getElementById('message-list');
    const messageInput = document.getElementById('message-input');
    const userList = document.getElementById('users');

    async function login() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        try {
            const response = await axios.post('/login', { username, password });
            currentUser = response.data.user_id;
            document.getElementById('login-form').style.display = 'none';
            document.getElementById('chat-container').style.display = 'flex';
            connectWebSocket();
            loadUsers();
        } catch (error) {
            alert('Login failed: ' + error.response.data.message);
        }
    }

    async function register() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        try {
            const response = await axios.post('/register', { username, password });
            alert('Registration successful. Please login.');
        } catch (error) {
            alert('Registration failed: ' + error.response.data.message);
        }
    }

    function connectWebSocket() {
        // socket = new WebSocket(`wss://${location.host}/ws`);
        socket = new WebSocket(`ws://${location.host}/ws`);
        socket.onopen = function() {
            socket.send(JSON.stringify({
                username: document.getElementById('username').value,
                password: document.getElementById('password').value
            }));
        };
        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            if (data.success === false) {
                alert('WebSocket authentication failed: ' + data.message);
                return;
            }
            if (data.user_id) {
                currentUser = data.user_id;
            } else {
                displayMessage(data);
            }
        };
        socket.onclose = function() {
            alert('WebSocket connection closed. Please refresh the page.');
        };
    }

    function displayMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.className = 'message';
        messageElement.innerHTML = `<span class="sender">${message.sender_id}</span>: ${message.content}`;
        messageList.appendChild(messageElement);
        messageList.scrollTop = messageList.scrollHeight;
    }

    function sendMessage() {
        const content = messageInput.value.trim();
        if (content) {
            const receiver = document.querySelector('input[name="user"]:checked');
            if (receiver) {
                const message = {
                    type: 'chat',
                    sender_id: currentUser,
                    receiver_id: parseInt(receiver.value),
                    content: content
                };
                socket.send(JSON.stringify(message));
                messageInput.value = '';
                displayMessage(message);
            } else {
                alert('Please select a recipient.');
            }
        }
    }

    async function loadUsers() {
        try {
            const response = await axios.get('/users');
            userList.innerHTML = '';
            response.data.users.forEach(user => {
                if (user.id !== currentUser) {
                    const userElement = document.createElement('li');
                    userElement.innerHTML = `
                        <input type="radio" name="user" value="${user.id}" id="user-${user.id}">
                        <label for="user-${user.id}">${user.username}</label>
                    `;
                    userList.appendChild(userElement);
                }
            });
        } catch (error) {
            console.error('Failed to load users:', error);
        }
    }

    // 添加回车发送消息的功能
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 定期刷新用户列表
    setInterval(loadUsers, 30000);
</script>
</body>
</html>
